package com.mhd.mq_to_es.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mhd.entity.TUserCoupon;
import com.mhd.mq_to_es.esvo.CouponInfo;
import com.mhd.mq_to_es.esvo.CouponUserRepository;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import com.rabbitmq.client.Channel;

@Component
public class EsConsumer {
    @Resource
    CouponUserRepository couponUserRepository;

    @RabbitListener(queues = "couponToES")
    public void couponToES(Channel channel, Message message, String couponJson) throws IOException {

        //json -->Vote对象
        ObjectMapper objectMapper = new ObjectMapper();

        TUserCoupon tUserCoupon = objectMapper.readValue(couponJson, TUserCoupon.class);

        CouponInfo couponInfo = new CouponInfo();
        BeanUtils.copyProperties(tUserCoupon,couponInfo);

        couponUserRepository.save(couponInfo);

        System.out.println("----------------------------");
        System.out.println("写入ES成功");

        //手动ack
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
